import requests, json
from socket import timeout
from xBlog.models import Thinkpage_city

KEY = 'uovys1x9q23g6wbg'  # API key
UID = "UEF88092CB"  # 用户ID
API = 'https://api.thinkpage.cn/v3/weather/now.json'  # API URL，可替换为其他 URL
UNIT = 'c'  # 单位
LANGUAGE = 'zh-Hans'  # 查询结果的返回语言


def get_weather_info_by_city(city):
    city = '天津' if city == '火星' else city
    return fetch_weather(city)


def fetch_weather(location):
    location_id = Thinkpage_city.get_id_by_name(location)
    try:
        result = requests.get(API, params={
            'key': KEY,
            'location': location_id,
            'language': LANGUAGE,
            'unit': UNIT
        }, timeout=1)
        content = json.loads(result.text)['results'][0]
    except SyntaxError:
        return None, None
    except timeout:
        return None, None
    except KeyError:
        return None, None
    else:
        return content['now']['temperature'], content['now']['text']
